package com.gosling.cloudspace.service;

import com.gosling.cloudspace.common.exception.CommonException;
import com.gosling.cloudspace.tools.CsvToXlsxTool;
import com.gosling.cloudspace.tools.MD5Tool;
import com.gosling.cloudspace.tools.Sm2Tool;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;

/**
 * @email 1793327033@qq.com
 * @classname UtilsServiceImpl
 * @author: osc_lihonglin
 * @date: 2021/7/23 9:21
 */
@Service
public class UtilsServiceImpl {

    protected static Logger logger = LoggerFactory.getLogger(UtilsServiceImpl.class);

    /***
     * SenseFieldTool加密解密
     * @param file
     * @param rows
     * @param outPath
     * @return
     */
    public static void decryptMode(MultipartFile file, List<Integer> rows, String outPath) {
//        List<Object> list = DecodeTool.readMoreThan1000Row(file);
//        List<String> head = (List<String>) list.get(0);
//        List<Object> row;
//        List<List<Object>> data = new ArrayList<>();
//        for (int i = 1; i < list.size(); i++) {
//            row = (List<Object>) list.get(i);
//            if (ObjectUtil.isNull(row)) {
//                break;
//            }
//            for (Integer rowNumber : rows) {
//                if (row.size() < (rowNumber - 1)) {
//                    break;
//                }
//                try {
////                    row.set(rowNumber - 1, ObjectUtil.isEmpty(row.get(rowNumber - 1)) ? null : SenseFieldTool.encryptMode((String) row.get(rowNumber - 1)));
//                } catch (Exception e) {
//                }
//            }
//            data.add(row);
//        }
//        DecodeTool.writeBySimple(outPath, data, head);
    }

    public static void main(String[] args) {
        File file = new File("D:\\项目说明\\35、签章改造-2期\\找回accountId商户\\个人证件号accID汇总.xlsx");
        MultipartFile multipartFile = new CommonsMultipartFile(covertDiskFileItem(file));
        ArrayList<Integer> list = new ArrayList<>();
        list.add(2);
        decryptMode(multipartFile, list, "D:\\项目说明\\35、签章改造-2期\\找回accountId商户\\个人证件号accID汇总2.xlsx");
    }

    /**
     * 将文件转换为DiskFileItem便于feign的实现类生成传输文件
     *
     * @param file
     * @return
     */
    public static DiskFileItem covertDiskFileItem(File file) {
        DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
                MediaType.TEXT_PLAIN_VALUE, true, file.getName());

        try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }
        return fileItem;
    }

    /***
     * SM2加密
     *
     * @param large
     * @return
     */
    public String sm2Generate(String large) {
        try {
            KeyPair keyPair = Sm2Tool.generateSm2KeyPair();
            PublicKey aPublic = keyPair.getPublic();
            byte[] encoded = aPublic.getEncoded();
            byte[] largeBytes = large.getBytes(StandardCharsets.UTF_8);
            byte[] encode = Base64Utils.encode(Sm2Tool.encrypt(largeBytes, encoded));
            String result = new String(encode, StandardCharsets.UTF_8);
            logger.info("加密结果:{}", result);
            return StringUtils.isBlank(result) ? null : result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * SM2解密
     *
     * @param large
     * @return
     */
    public String sm2Decrypt(String large) {
        try {
            KeyPair keyPair = Sm2Tool.generateSm2KeyPair();
            PublicKey aPublic = keyPair.getPublic();
            byte[] encoded = aPublic.getEncoded();
            byte[] largeBytes = large.getBytes(StandardCharsets.UTF_8);
            byte[] encode = Base64Utils.encode(Sm2Tool.decrypt(encoded, largeBytes));
            String result = new String(encode, StandardCharsets.UTF_8);
            logger.info("解密结果:{}", result);
            return StringUtils.isBlank(result) ? null : result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * CSV转Excel精度丢失
     *
     * @return
     */
    public void csv2xlsx(MultipartFile file, HttpServletResponse response) {
        try {
            CsvToXlsxTool.csv2xlsx(file.getInputStream(), file.getOriginalFilename(), response);
        } catch (IOException e) {
            throw new CommonException("CSV转Excel失败");
        }
    }

}
